package com.example.text.service.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.text.dao.AdminPermissionDao;
import com.example.text.dao.AdminRolePermissionDao;
import com.example.text.entity.AdminPermission;
import com.example.text.entity.AdminRole;
import com.example.text.entity.AdminRolePermission;
import com.example.text.service.AdminPermissionService;
import com.example.text.service.AdminRolePermissionService;
import com.example.text.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AdminPermissionServiceImpl extends ServiceImpl<AdminPermissionDao, AdminPermission> implements AdminPermissionService {

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    AdminRolePermissionDao adminRolePermissionDao;

    @Autowired
    AdminRolePermissionService adminRolePermissionService;

    @Autowired
    AdminPermissionDao adminPermissionDao;

    public boolean needFilter(String requestAPI) {
        List<AdminPermission> ps = adminPermissionDao.findAll();
        for (AdminPermission p: ps) {
            // match prefix
            if (requestAPI.startsWith(p.getUrl())) {
                return true;
            }
        }
        return false;
    }

    public List<AdminPermission> listPermsByRoleId(int rid) {
        System.out.println("rid："+rid);
        List<Integer> pids = adminRolePermissionService.findAllByRid(rid)
                .stream().map(AdminRolePermission::getPid).collect(Collectors.toList());
        System.out.println("pids："+pids);
        if(!pids.isEmpty()){
            List<AdminPermission> adminPermissions=adminPermissionDao.findAllById(pids);
            System.out.println("管理者的规则："+adminPermissions);
            return adminPermissions;
        }else {
             return  null;
        }


    }

    public Set<String> listPermissionURLByUser(String username){

        //根据用户名，获得当前用户对应的所有角色的 id 列表（1：系统管理员，2：内容管理员，等）
        List<Integer> rids=adminRoleService.listRolesByUser(username)
                .stream().map(AdminRole::getId).collect(Collectors.toList());

        //根据rids. 查询出这些角色对应的管理的pids
        List<Integer> pids=adminRolePermissionDao.findAllByRid(rids)
                .stream().map(AdminRolePermission::getPid).collect(Collectors.toList());

        //根据pid 查询对应管理功能，如1：用户管理，2：角色管理
        List<AdminPermission> perms=adminPermissionDao.findAllById(pids);

        //获取对应管理功能的url
        Set<String> URLs=perms.stream().map(AdminPermission::getUrl).collect(Collectors.toSet());

        return URLs;
    }
}
